package com.jcl.emessage.core.handler;

import com.jcl.core.utils.CollectionUtils;
import com.jcl.emessage.core.config.EmailConfig;
import com.jcl.emessage.core.exception.SendEmailException;
import com.jcl.emessage.core.vo.MailMessageVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.Map;

/**
 * @ClassName SendEmailHandler
 * @Description TODO
 * @Author yyliu
 * @Date 2018/9/18 10:01
 * @Version 1.0
 **/
@Component
public class SendEmailHandler {

    private static final Logger logger = LoggerFactory.getLogger(SendEmailHandler.class);

    @Autowired
    private EmailConfig emailConfig;
    @Autowired
    private JavaMailSender mailSender;
    @Autowired
    private TemplateEngine templateEngine;


    /* *
     * @Author yyliu
     * @Description //TODO
     * @Date 13:32 2018/9/17
     * @Param [mailInfo]
     * @return int 0-Y
     **/
    public int sendHtmlMail(MailMessageVo vo) {

        int success = 0;
        try {
            send(vo);
            return success;
        } catch (SendEmailException e) {
            success = 1;
            logger.error(e.getMessage(), e);
        } catch (MessagingException e) {
            success = 2;
            logger.error(e.getMessage(), e);
        }
        return success;
    }

    /* *
     * @Author yyliu
     * @Description
     * @Date 13:39 2018/9/17
     * @Param [mailInfo]
     * @return int 0-Y
     **/
    public int sendAttachmentMail(MailMessageVo vo) {

        int success = 0;
        try {
            send(vo);
            return success;
        } catch (SendEmailException e) {
            success = 1;
            logger.error(e.getMessage(), e);
        } catch (MessagingException e) {
            success = 2;
            logger.error(e.getMessage(), e);
        }
        return success;
    }

    /* *
     * @Author yyliu
     * @Description 静态文件（图片）
     * @Date 13:42 2018/9/17
     * @Param [mailInfo]
     * @return int 0-Y
     **/
    public int sendInlineResourceMail(MailMessageVo vo) {

        int success = 0;
        try {
            send(vo);
            return success;
        } catch (SendEmailException e) {
            success = 1;
            logger.error(e.getMessage(), e);
        } catch (MessagingException e) {
            success = 2;
            logger.error(e.getMessage(), e);
        }
        return success;
    }

    /* *
     * @Author yyliu
     * @Description 通过模板返回信息
     * @Date 16:02 2018/9/17
     * @Param [templateName, params]
     * @return java.lang.String
     **/
    public String templateContent(String templateName, Map<String, Object> params) {
        Context context = new Context();
        context.clearVariables();
        if (CollectionUtils.isNotEmpty(params)) {
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                context.setVariable(entry.getKey(), entry.getValue());
            }
        }

        return templateEngine.process(templateName, context);
    }

    /* *
     * @Author yyliu
     * @Description //TODO
     * @Date 13:39 2018/9/17
     * @Param [mailInfo]
     * @return void
     **/
    private MimeMessage initMimeMessage(MailMessageVo vo) throws MessagingException {

        MimeMessage message = mailSender.createMimeMessage();

        MimeMessageHelper helper = new MimeMessageHelper(message, true);

        helper.setSubject(vo.getSubject());
        helper.setFrom(vo.getFrom());
        helper.setTo(vo.getTo());
        helper.setText(vo.getContent(), true);

        // 文件处理附件
        if (CollectionUtils.isNotEmpty(vo.getFileList())) {
            for (File f : vo.getFileList()) {
                FileSystemResource res = new FileSystemResource(f);
                String fileName = f.getName();
                helper.addAttachment(fileName, res);
            }
        }

        // 处理静态图片
        if (CollectionUtils.isNotEmpty(vo.getResourceMap())) {
            for (Map.Entry<String, String> entry : vo.getResourceMap().entrySet()) {
                FileSystemResource res = new FileSystemResource(new File(entry.getKey()));
                helper.addInline(entry.getValue(), res);
            }
        }

        return message;
    }

    private void send(MailMessageVo vo) throws MessagingException {

        MimeMessage message = initMimeMessage(vo);

        if (null != message) {

            logger.debug("发送地址：{}", vo.getFrom());
            logger.debug("收件人：{}", vo.getTo());
            logger.debug("发送内容：{}", vo.getContent());

            boolean success = false;
            int time = 0;
            Integer tryTime = emailConfig.getTryTime();
            tryTime = null == tryTime ? 3 : tryTime;

            logger.info("START SEND EMAIL ......");
            while (!success && time < tryTime) {
                try {
                    logger.info("send email time[{}] ", time);
                    mailSender.send(message);
                    success = true;

                } catch (MailException e) {

                    logger.error(e.getMessage(), e);

                    logger.info("send email time[{}] fail, try again!", time);

                    time++;
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e1) {
                        logger.warn(e1.getMessage(), e1);
                    }
                    if (time >= tryTime) {
                        throw new SendEmailException(e.getMessage(), e);
                    }
                }
            }
            logger.info("START SEND END ......");
        }
    }


}